package admin

import (
	"github.com/gin-gonic/gin"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"time"
)

// 获取会员等级
func LevelList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MMemberLevel
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	tx := models.DB.Model(new(models.MMemberLevel)).Where("aid=? AND name LIKE ?", jsonData.Aid, "%"+jsonData.Name+"%")
	if jsonData.SubName != "" {
		tx = tx.Where("sub_name LIKE ?", "%"+jsonData.SubName+"%")
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Find(&list)
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 新增/修改会员等级
func LevelAdd(c *gin.Context) {
	//获取传值
	var jsonData models.MMemberLevel
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	if jsonData.ID > 0 {
		//修改数据
		var editData = map[string]interface{}{
			"name":                 jsonData.Name,
			"sub_name":             jsonData.SubName,
			"icon":                 jsonData.Icon,
			"discount":             jsonData.Discount,
			"maxnum":               jsonData.Maxnum,
			"can_up":               jsonData.CanUp,
			"up_condition_show":    jsonData.UpConditionShow,
			"up_ordermoney":        jsonData.UpOrdermoney,
			"up_rechargemoney":     jsonData.UpRechargemoney,
			"up_give_score":        jsonData.UpGiveScore,
			"up_give_money":        jsonData.UpGiveMoney,
			"up_give_commission":   jsonData.UpGiveCommission,
			"up_give_parent_money": jsonData.UpGiveParentMoney,
			"can_agent":            jsonData.CanAgent,
			"commissiontype":       jsonData.Commissiontype,
			"commission1":          jsonData.Commission1,
			"commission2":          jsonData.Commission2,
			"commission3":          jsonData.Commission3,
			"score1":               jsonData.Score1,
			"score2":               jsonData.Score2,
			"score3":               jsonData.Score3,
			"scoremax":             jsonData.Scoremax,
			"yxqdate":              jsonData.Yxqdate,
			"explain":              jsonData.Explain,
		}
		err = models.DB.Model(new(models.MMemberLevel)).Where("id=?", jsonData.ID).Updates(&editData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10003,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，修改了会员等级:" + strconv.Itoa(jsonData.ID) + "的内容"
		models.LogAdd(3, "修改会员等级", userId, logData, bid, jsonData.Aid)
	} else {
		var data models.MMemberLevel
		data.Aid = jsonData.Aid
		data.Name = jsonData.Name
		data.SubName = jsonData.SubName
		data.Icon = jsonData.Icon
		data.Discount = jsonData.Discount
		data.Maxnum = jsonData.Maxnum
		data.CanUp = jsonData.CanUp
		data.UpConditionShow = jsonData.UpConditionShow
		data.UpOrdermoney = jsonData.UpOrdermoney
		data.UpRechargemoney = jsonData.UpRechargemoney
		data.CanAgent = jsonData.CanAgent
		data.Commission1 = jsonData.Commission1
		data.Commission2 = jsonData.Commission2
		data.Commission3 = jsonData.Commission3
		data.Score1 = jsonData.Score1
		data.Score3 = jsonData.Score2
		data.Score3 = jsonData.Score3
		data.Explain = jsonData.Explain
		data.Createtime = int(time.Now().Unix())
		data.Yxqdate = jsonData.Yxqdate
		data.Commissiontype = jsonData.Commissiontype
		data.Scoremax = jsonData.Scoremax
		data.UpGiveMoney = jsonData.UpGiveMoney
		data.UpGiveScore = jsonData.UpGiveScore
		data.UpGiveCommission = jsonData.UpGiveCommission
		data.UpGiveParentMoney = jsonData.UpGiveParentMoney
		data.Sort = 0
		data.Comwithdraw = 1
		data.CommissionMax = 0
		err = models.DB.Model(new(models.MMemberLevel)).Create(&data).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10001,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，新增了一个会员等级:" + jsonData.Name
		models.LogAdd(2, "新增会员等级", userId, logData, bid, jsonData.Aid)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 删除会员等级
func LevelDel(c *gin.Context) {
	var jsonData models.MMemberLevel
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MMemberLevel
	models.DB.Model(new(models.MMemberLevel)).Where("id=?", jsonData.ID).First(&data)
	tx := models.DB.Begin()

	//删除
	err = tx.Delete(&models.MMemberLevel{}, jsonData.ID).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	tx.Commit()

	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，删除了一个会员等级:" + data.Name
	models.LogAdd(4, "删除会员等级", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 会员等级排序
func LevelSort(c *gin.Context) {
	//接收id
	var jsonData models.MMemberLevel
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MMemberLevel
	models.DB.Model(new(models.MMemberLevel)).Where("id=?", jsonData.ID).First(&data)
	//修改
	err = models.DB.Model(new(models.MMemberLevel)).Where("id=?", jsonData.ID).Update("sort", jsonData.Sort).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10002,
			"msg":  err.Error(),
		})
		return
	}
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，修改会员等级:" + data.Name + "的排序"
	models.LogAdd(5, "会员等级", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}
